package com.inno.auth.domain.strategy;

import cn.hutool.core.util.IdUtil;
import com.inno.auth.common.enums.IsDeletedFlagEnum;
import com.inno.auth.common.enums.LoginTypeEnum;
import com.inno.auth.common.enums.YesOrNoEnum;
import com.inno.auth.common.error.AuthException;
import com.inno.auth.common.utils.DateUtils;
import com.inno.auth.infra.basic.entity.PlannerUsers;
import com.inno.auth.infra.basic.service.PlannerUsersService;
import com.inno.auth.infra.rpc.SmsRpc;
import com.inno.sms.dto.SmsInfoDTO;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;

/**
 * 手机号短信登录
 * @author sean
 */
@Component
public class ShortMessageLoginHandler implements LoginHandler{

    private final PlannerUsersService plannerUsersService;
    private final SmsRpc smsRpc;
    public ShortMessageLoginHandler(PlannerUsersService plannerUsersService,SmsRpc smsRpc){
        this.plannerUsersService = plannerUsersService;
        this.smsRpc = smsRpc;
    }

    @Override
    public LoginTypeEnum getType() {
        return LoginTypeEnum.LOGIN_TYPE_SHORT_MESSAGE;
    }

    @Override
    public PlannerUsers login(PlannerUsers users) {
        SmsInfoDTO smsInfoDTO = new SmsInfoDTO();
        smsInfoDTO.setSmsContent(users.getCode());
        smsInfoDTO.setMobile(users.getMobile());
        boolean validate = this.smsRpc.validate(smsInfoDTO);
        if (!validate){
            throw new AuthException("验证码无效");
        }
        PlannerUsers usersDb = this.plannerUsersService.queryByMobile(users.getMobile());

        if (Objects.isNull(usersDb)){
            // 新用户 注册
            usersDb = new PlannerUsers();
            long snowflakeNextId = IdUtil.getSnowflakeNextId();
            usersDb.setId(snowflakeNextId);
            Date nowDate = DateUtils.getNowDate();
            usersDb.setCreateTime(nowDate);
            usersDb.setRegisterTime(nowDate);
            usersDb.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode().toString());
            usersDb.setGender(YesOrNoEnum.YES.getCode());
            usersDb.setMobile(users.getMobile());
            plannerUsersService.insert(usersDb);
        }
        return usersDb;
    }
}
